<template>
  <a-modal
    :title="title"
    width="80%"
    :dialog-style="{ top: '20px' }"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleSubmit"
    @cancel="close"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="标题"
        >
          <a-input placeholder="请输入文章标题" v-decorator="[ 'title', {rules: [{ required: true, message: '请输入文章标题!' }]}]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="摘要"
        >
          <a-input placeholder="请输入文章摘要" v-decorator="[ 'summary', {rules: [{ required: false, message: '请输入文章摘要!' }]}]"/>
        </a-form-item>

        <a-form-item
          label="分类"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <tree-select
            style="width:100%"
            :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
            :treeData="treeData"
            v-decorator="['varietyId', {rules: [{ required: true, message: '请选择文章的分类!' }]}]"
            placeholder="请选择文章的分类"
          >
          </tree-select>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="正文"
        >c
          <editor v-decorator="[ 'detail', {rules: [{ required: true, message: '请输入正文!' }]}]" triggerChange></editor>
        </a-form-item>

      </a-form>
    </a-spin>

    <div slot="footer">
      <a-button :style="{marginRight: '8px'}" @click="close">取消</a-button>
      <a-button @click="handleSubmit(articleStatusEnum.INIT.KEY)" type="primary" :loading="confirmLoading">保存到草稿</a-button>
      <a-button @click="handleSubmit(articleStatusEnum.ENABLE.KEY)" type="primary" :loading="confirmLoading">保存并发布</a-button>
    </div>

  </a-modal>
</template>

<script>
import { FormModalMixin } from '@/mixins/FormModalMixin'
import { TreeSelect } from 'ant-design-vue'
import Editor from '@/components/editor/Editor'
import pick from 'lodash.pick'
import { ARTICLE_STATUS_ENUM } from '@/store/mutation-types'

import { apiQueryArticleVarietyTree, apiSaveArticle, apiUpdateArticle, apiQueryArticleById } from '@/api/article'

export default {
  name: 'ArticleModal',
  components: {
    TreeSelect, Editor
  },
  mixins: [FormModalMixin],
  data () {
    return {
      treeData: [],
      articleStatusEnum: ARTICLE_STATUS_ENUM
    }
  },
  methods: {
    async show (title, record) {
      this.resetFields()
      this.model = {}
      this.visible = true
      this.title = title
      await this.loadVarietyTree()
      if (record) {
        apiQueryArticleById(record.id).then(res => {
          this.model = Object.assign({}, res.data)
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model, 'title', 'varietyId', 'summary', 'detail'))
          })
        })
      }
    },
    loadVarietyTree () {
      const that = this
      apiQueryArticleVarietyTree().then(res => {
        that.treeData = that.getTreeData(res.data)
      })
    },
    getTreeData (list) {
      const treeData = []
      for (let i = 0; i < list.length; i++) {
        const temp = {
          title: list[i].name,
          value: list[i].id,
          key: list[i].id
        }
        if (list[i].children !== null && list[i].children.length > 0) {
          temp.children = [...this.getTreeData(list[i].children)]
        }
        treeData.push(temp)
      }
      return treeData
    },
    handleSubmit (status) {
      console.log(this.form)
      this.form.validateFields((err, values) => {
        if (!err) {
          const formData = pick(Object.assign(this.model, values), 'title', 'varietyId', 'summary', 'status', 'detail')
          formData.status = status
          if (formData.summary == null) {
            formData.summary = ''
          }
          this.confirmLoading = true
          let obj
          if (this.model.id) {
            obj = apiUpdateArticle(this.model.id, formData)
          } else {
            obj = apiSaveArticle(formData)
          }
          obj.then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg)
              this.$emit('ok')
              this.close()
            } else {
              this.$message.warning(res.msg)
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
